<template>
  <div class="recording-sync-test p-4 border border-dashed border-gray-300 rounded-lg bg-gray-50">
    <h3 class="text-lg font-medium mb-4">录制同步测试</h3>
    
    <!-- 录制状态显示 -->
    <div class="mb-4">
      <div class="flex items-center space-x-4">
        <div class="flex items-center">
          <div 
            :class="[
              'w-3 h-3 rounded-full mr-2',
              isRecording ? 'bg-red-500 animate-pulse' : 'bg-gray-300'
            ]"
          ></div>
          <span class="text-sm">
            {{ isRecording ? '正在录制' : '未录制' }}
          </span>
        </div>
        
        <div class="text-sm text-gray-600">
          步骤数量: {{ recordingSteps.length }}
        </div>
        
        <div class="text-sm text-gray-600">
          录制时长: {{ formattedDuration }}
        </div>
      </div>
    </div>
    
    <!-- 控制按钮 -->
    <div class="flex space-x-2 mb-4">
      <el-button 
        type="primary" 
        size="small"
        :disabled="isRecording"
        @click="startTestRecording"
      >
        开始测试录制
      </el-button>
      
      <el-button 
        type="danger" 
        size="small"
        :disabled="!isRecording"
        @click="stopTestRecording"
      >
        停止录制
      </el-button>
      
      <el-button 
        size="small"
        @click="addMockStep"
        :disabled="!isRecording"
      >
        添加模拟步骤
      </el-button>
      
      <el-button 
        size="small"
        @click="clearSteps"
      >
        清空步骤
      </el-button>
    </div>
    
    <!-- 实时步骤列表 -->
    <div class="bg-white rounded border p-3">
      <h4 class="text-sm font-medium mb-2">实时步骤列表</h4>
      <div v-if="recordingSteps.length === 0" class="text-gray-500 text-sm">
        暂无录制步骤
      </div>
      <div v-else class="space-y-1">
        <div 
          v-for="step in recordingSteps" 
          :key="step.stepNumber"
          class="flex items-center justify-between p-2 bg-gray-50 rounded text-sm"
        >
          <div class="flex items-center space-x-2">
            <span class="font-mono text-xs bg-blue-100 text-blue-800 px-1 rounded">
              {{ step.stepNumber }}
            </span>
            <span class="font-medium">{{ step.name }}</span>
            <span class="text-gray-500">{{ step.type }}</span>
          </div>
          <span class="text-xs text-gray-400">
            {{ formatTime(step.timestamp) }}
          </span>
        </div>
      </div>
    </div>
    
    <!-- 事件日志 -->
    <div class="mt-4 bg-white rounded border p-3">
      <h4 class="text-sm font-medium mb-2">事件日志</h4>
      <div class="max-h-32 overflow-y-auto">
        <div 
          v-for="log in eventLogs" 
          :key="log.id"
          class="text-xs text-gray-600 mb-1"
        >
          <span class="text-gray-400">{{ formatTime(log.timestamp) }}</span>
          <span class="ml-2">{{ log.message }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRecordingStore } from '../stores/recording'
import { ElButton, ElMessage } from 'element-plus'

const recordingStore = useRecordingStore()

// 响应式数据
const eventLogs = ref([])
const mockStepCounter = ref(0)

// 计算属性
const isRecording = computed(() => recordingStore.isRecording)
const recordingSteps = computed(() => recordingStore.recordingSteps)
const formattedDuration = computed(() => recordingStore.formattedDuration)

// 事件监听器
let stepRecordedHandler = null
let recordingStatusHandler = null
let stepAddedHandler = null

onMounted(() => {
  setupEventListeners()
  addLog('组件已挂载，开始监听录制事件')
})

onUnmounted(() => {
  cleanupEventListeners()
})

// 设置事件监听器
const setupEventListeners = () => {
  if (typeof window !== 'undefined') {
    // 监听步骤录制事件
    stepRecordedHandler = (event) => {
      const { step } = event.detail
      addLog(`收到步骤录制事件: ${step.name}`)
    }
    
    // 监听录制状态更新事件
    recordingStatusHandler = (event) => {
      const { stepCount } = event.detail
      addLog(`录制状态更新: ${stepCount} 个步骤`)
    }
    
    // 监听UI步骤添加事件
    stepAddedHandler = (event) => {
      const { step } = event.detail
      addLog(`UI步骤添加: ${step.name}`)
    }
    
    window.addEventListener('stepRecorded', stepRecordedHandler)
    window.addEventListener('recordingStatusUpdated', recordingStatusHandler)
    window.addEventListener('stepAddedToUI', stepAddedHandler)
  }
}

// 清理事件监听器
const cleanupEventListeners = () => {
  if (typeof window !== 'undefined') {
    if (stepRecordedHandler) {
      window.removeEventListener('stepRecorded', stepRecordedHandler)
    }
    if (recordingStatusHandler) {
      window.removeEventListener('recordingStatusUpdated', recordingStatusHandler)
    }
    if (stepAddedHandler) {
      window.removeEventListener('stepAddedToUI', stepAddedHandler)
    }
  }
}

// 开始测试录制
const startTestRecording = async () => {
  try {
    addLog('开始测试录制...')
    const result = await recordingStore.startRecording({
      startUrl: 'https://example.com',
      name: '同步测试录制'
    })
    
    if (result.success) {
      addLog(`录制已启动 (会话ID: ${result.sessionId})`)
      ElMessage.success('测试录制已启动')
    } else {
      addLog(`录制启动失败: ${result.error}`)
      ElMessage.error('录制启动失败: ' + result.error)
    }
  } catch (error) {
    addLog(`录制启动异常: ${error.message}`)
    ElMessage.error('录制启动异常: ' + error.message)
  }
}

// 停止测试录制
const stopTestRecording = async () => {
  try {
    addLog('停止测试录制...')
    const result = await recordingStore.stopRecording()
    
    if (result.success) {
      addLog(`录制已停止，共 ${result.steps?.length || 0} 个步骤`)
      ElMessage.success('测试录制已停止')
    } else {
      addLog(`录制停止失败: ${result.error}`)
      ElMessage.error('录制停止失败: ' + result.error)
    }
  } catch (error) {
    addLog(`录制停止异常: ${error.message}`)
    ElMessage.error('录制停止异常: ' + error.message)
  }
}

// 添加模拟步骤
const addMockStep = () => {
  if (!isRecording.value) {
    ElMessage.warning('请先开始录制')
    return
  }
  
  mockStepCounter.value++
  
  const mockSteps = [
    {
      type: 'navigation',
      name: '导航到页面',
      description: '打开网页',
      url: 'https://example.com',
      selector: 'https://example.com'
    },
    {
      type: 'input',
      name: '输入用户名',
      description: '填写用户名',
      selector: '#username',
      value: 'testuser'
    },
    {
      type: 'click',
      name: '点击登录按钮',
      description: '点击登录',
      selector: '#login-btn'
    },
    {
      type: 'assertion',
      name: '验证登录成功',
      description: '检查页面标题',
      selector: 'h1',
      assertion: 'toBeVisible'
    }
  ]
  
  const mockStep = mockSteps[mockStepCounter.value % mockSteps.length]
  
  const step = recordingStore.addRecordedStep(mockStep)
  
  if (step) {
    addLog(`添加模拟步骤: ${step.name}`)
    ElMessage.success('已添加模拟步骤')
  } else {
    addLog('添加模拟步骤失败')
    ElMessage.error('添加模拟步骤失败')
  }
}

// 清空步骤
const clearSteps = () => {
  recordingStore.clearRecordedSteps()
  addLog('已清空所有步骤')
  ElMessage.info('已清空所有步骤')
}

// 添加日志
const addLog = (message) => {
  eventLogs.value.push({
    id: Date.now() + Math.random(),
    timestamp: new Date(),
    message
  })
  
  // 限制日志数量
  if (eventLogs.value.length > 50) {
    eventLogs.value = eventLogs.value.slice(-50)
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString()
}
</script>

<style scoped>
.recording-sync-test {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}
</style>
